﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using CI.Models.Data;
using log4net;

namespace XmlModelPackager
{
    public class TypeCategoriesXmlGenerator : XmlGeneratorBase, IXmlGenerator
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(TypeCategoriesXmlGenerator));

        public TypeCategoriesXmlGenerator()
            : base(new FileInfo("categories.xml"), "Category")
        {
        }


        protected TyrannisDataContext GetDataContext()
        {
            return new TyrannisDataContext(ConfigurationManager.ConnectionStrings["TyrannisDB"].ConnectionString);
        }

        public void GenerateXml()
        {
            using (var ctx = GetDataContext())
            {
                var categories = ctx.invCategories.OrderBy(c => c.categoryID);

                foreach(var category in categories)
                {
                    _logger.DebugFormat("Processing {0}:{1}", category.categoryID, category.categoryName);

                    BeginElement("Category");

                    WriteAttributes(category, "categoryID", "categoryName", "description", "graphicID", "published");

                    var groups = ctx.invGroups.Where(g => g.categoryID == category.categoryID);

                    foreach(var group in groups)
                    {
                        BeginElement("Group");

                        WriteAttributes(group, "groupID", "groupName", "description", "graphicID", "useBasePrice",
                                        "allowManufacture", "allowRecycler", "anchored", "anchorable",
                                        "fittableNonSingleton", "published");

                        EndElement();
                    }

                    EndElement();
                }
            }
        }
    }
}
